#!/bin/bash

###############################################################################
# 军事数据加工平台 - 自动部署脚本
# 
# 使用方法：
# 1. chmod +x deploy.sh
# 2. ./deploy.sh
#
# 注意：首次部署请先手动配置环境变量和数据库
###############################################################################

set -e  # 遇到错误立即退出

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 配置项
PROJECT_DIR="/var/www/janes"
FRONTEND_DIR="/var/www/janes-frontend"
APP_NAME="janes-backend"

# 打印带颜色的消息
print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_step() {
    echo -e "\n${BLUE}==== $1 ====${NC}\n"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 未安装，请先安装"
        exit 1
    fi
}

# 检查必要的命令
print_step "检查环境依赖"
check_command node
check_command pnpm
check_command pm2
check_command nginx
print_success "所有依赖已安装"

# 1. 拉取最新代码
print_step "[1/7] 拉取最新代码"
cd $PROJECT_DIR
if [ -d ".git" ]; then
    git pull origin master
    print_success "代码已更新"
else
    print_warning "不是 Git 仓库，跳过代码更新"
fi

# 2. 备份当前版本（可选）
print_step "[2/7] 备份当前版本"
BACKUP_DIR="/var/backups/janes/$(date +%Y%m%d_%H%M%S)"
mkdir -p $BACKUP_DIR
if [ -d "$FRONTEND_DIR" ]; then
    cp -r $FRONTEND_DIR $BACKUP_DIR/frontend
    print_success "前端已备份到 $BACKUP_DIR"
fi

# 3. 安装/更新后端依赖
print_step "[3/7] 更新后端依赖"
cd $PROJECT_DIR
pnpm install --prod
print_success "后端依赖已更新"

# 4. 构建前端
print_step "[4/7] 构建前端"
cd $PROJECT_DIR/frontend
pnpm install
pnpm run build
print_success "前端构建完成"

# 5. 部署前端文件
print_step "[5/7] 部署前端文件"
sudo mkdir -p $FRONTEND_DIR
sudo cp -r dist/* $FRONTEND_DIR/
sudo chown -R www-data:www-data $FRONTEND_DIR
print_success "前端文件已部署"

# 6. 重启后端服务
print_step "[6/7] 重启后端服务"
cd $PROJECT_DIR
if pm2 describe $APP_NAME > /dev/null 2>&1; then
    pm2 reload $APP_NAME
    print_success "后端服务已重启"
else
    print_warning "后端服务未运行，尝试启动..."
    pm2 start ecosystem.config.js
    print_success "后端服务已启动"
fi

# 7. 重启 Nginx
print_step "[7/7] 重启 Nginx"
sudo nginx -t
if [ $? -eq 0 ]; then
    sudo systemctl reload nginx
    print_success "Nginx 已重启"
else
    print_error "Nginx 配置检查失败，请检查配置"
    exit 1
fi

# 完成
echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}🎉 部署完成！${NC}"
echo -e "${GREEN}========================================${NC}\n"

print_info "服务信息："
echo -e "  前端地址: http://your-domain.com"
echo -e "  后端 API: http://your-domain.com/api"
echo -e "  健康检查: http://your-domain.com/health"

echo -e "\n${BLUE}服务状态：${NC}"
pm2 status

echo -e "\n${BLUE}最近日志：${NC}"
pm2 logs $APP_NAME --lines 10 --nostream

echo -e "\n${YELLOW}提示：${NC}"
echo -e "  - 查看日志: pm2 logs $APP_NAME"
echo -e "  - 监控服务: pm2 monit"
echo -e "  - 重启服务: pm2 restart $APP_NAME"
echo -e "  - Nginx日志: sudo tail -f /var/log/nginx/janes_error.log"

